require('dotenv').config(); 
const mongoose = require('mongoose');
const fs = require('fs');
const path = require('path');
const CampusNotice = require('./src/models/CampusNotice');
const HotTopic = require('./src/models/HotTopic');
const Activity = require('./src/models/Activity');
const MarketItem = require('./src/models/MarketItem');

function getBase64FromFile(imageName) {
  try {
    // 从 downloads 目录读取 base64 文件
    const base64Path = path.resolve(__dirname, '../downloads', imageName.replace('.jpg', '.base64.txt'));
    if (fs.existsSync(base64Path)) {
      const base64Content = fs.readFileSync(base64Path, 'utf8');
      return base64Content;
    }
    console.warn(`Base64 file not found for ${imageName}, using default image`);
    return null;
  } catch (error) {
    console.error(`Error reading base64 file for ${imageName}:`, error);
    return null;
  }
}

// 直接在此处连接数据库，避免依赖 connectDB 封装
async function seedHomeData() {
  try {
    await mongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost:27017/campus');
    console.log('MongoDB连接成功');

    // 清空现有数据
    await Promise.all([
      CampusNotice.deleteMany({}),
      HotTopic.deleteMany({}),
      Activity.deleteMany({}),
      MarketItem.deleteMany({})
    ]);
    console.log('已清空现有数据');

    // 创建校园通知
    const notices = [
      {
        title: '关于2025年秋季学期选课的通知',
        content: '为确保选课工作顺利进行，现将2025年秋季学期选课相关事项通知如下...',
        cover: getBase64FromFile('class.jpg'),
        date: new Date('2025-06-01'),
        category: 'academic'
      },
      {
        title: '图书馆闭馆时间调整通知',
        content: '因系统升级维护，图书馆将于本周末临时调整开放时间...',
        cover: getBase64FromFile('library.jpg'),
        date: new Date('2025-06-02'),
        category: 'facility'
      },
      {
        title: '关于开展核酸检测的重要通知',
        content: '为进一步做好疫情防控工作，学校将于本周开展全员核酸检测...',
        cover: getBase64FromFile('covid.jpg'),
        date: new Date('2025-06-03'),
        category: 'health'
      },
      {
        title: '2025届毕业生学位申请通知',
        content: '请各位2025届毕业生注意学位申请的截止时间...',
        cover: getBase64FromFile('exam.jpg'),
        date: new Date('2025-06-04'),
        category: 'academic'
      }
    ];

    // 创建热门话题
    const topics = [
      {
        title: '校园新食堂征名投票',
        content: '新建成的第五食堂即将投入使用，现面向全校师生征集食堂名称...',
        count: 2580,
        tags: ['校园建设', '美食']
      },
      {
        title: '暑期实习经验分享',
        content: '欢迎同学们分享各自的实习经历，为学弟学妹提供参考...',
        count: 1890,
        tags: ['实习', '就业'],
        cover: getBase64FromFile('practice.jpg')
      },
      {
        title: '校园歌手大赛报名',
        content: '第十届校园歌手大赛开始报名啦！展示你的才艺...',
        count: 1560,
        tags: ['文艺', '比赛'],
        cover: getBase64FromFile('carnival.jpg')
      },
      {
        title: '宿舍空调使用问题',
        content: '关于宿舍空调收费标准和使用时间的讨论...',
        count: 1230,
        tags: ['宿舍', '生活'],
        cover: getBase64FromFile('dorm.jpg')
      },
      {
        title: '图书馆自习室预约系统优化建议',
        content: '针对目前自习室预约系统存在的问题，收集同学们的建议...',
        count: 980,
        tags: ['图书馆', '学习']
      },
      {
        title: '校园运动会项目投票',
        content: '今年校运会将新增两个比赛项目，请投票选择...',
        count: 850,
        tags: ['体育', '活动'],
        cover: getBase64FromFile('sports.jpg')
      }
    ];

    // 创建校园活动
    const activities = [
      {
        title: '2025届毕业生专场招聘会',
        description: '携手500强企业，为毕业生提供优质就业机会...',
        location: '大学生活动中心',
        startTime: new Date('2025-06-15T09:00:00'),
        endTime: new Date('2025-06-15T17:00:00'),
        cover: getBase64FromFile('jobfair.jpg'),
        category: 'career'
      },
      {
        title: '人工智能发展前沿讲座',
        description: '邀请行业专家分享AI最新技术趋势...',
        location: '图书馆报告厅',
        startTime: new Date('2025-06-20T14:00:00'),
        endTime: new Date('2025-06-20T16:00:00'),
        cover: getBase64FromFile('lecture.jpg'),
        category: 'academic'
      }
    ];

    // 创建市场物品
    const marketItems = [
      {
        title: '全新iPad Pro',
        description: '2024款iPad Pro，256G，太空灰，未拆封',
        price: 5999,
        category: 'digital',
        images: [getBase64FromFile('market1.jpg')],
        condition: 'new'
      },
      {
        title: '二手自行车',
        description: '捷安特自行车，使用8个月，性能完好',
        price: 680,
        category: 'transportation',
        images: [getBase64FromFile('market2.jpg')],
        condition: 'good'
      }
    ];

    // 插入数据
    console.log('开始插入数据...');
    await Promise.all([
      CampusNotice.insertMany(notices),
      HotTopic.insertMany(topics),
      Activity.insertMany(activities),
      MarketItem.insertMany(marketItems)
    ]);

    console.log('数据初始化成功！');
  } catch (error) {
    console.error('数据初始化失败：', error);
  } finally {
    await mongoose.disconnect();
    console.log('MongoDB 连接已关闭');
    process.exit(0);
  }
  try {
    await mongoose.connect(process.env.MONGODB_URI);
    // 清空旧数据
    await CampusNotice.deleteMany({});
    await HotTopic.deleteMany({});
    await Activity.deleteMany({});
    await MarketItem.deleteMany({});

    // 转换通知图片为base64
    const noticeImage = getBase64FromImage('library.jpg');
    await CampusNotice.insertMany([
      { 
        tag: '重要', 
        title: '关于图书馆闭馆的通知', 
        date: '2023-10-15',
        content: '因图书盘点与整理工作，本周五图书馆闭馆一天，后续开放时间不变，望周知。',
        type: '图书馆通知',
        image: noticeImage
      },
      { 
        tag: '活动', 
        title: '校园招聘会安排', 
        date: '2023-10-14',
        content: '本月底将举办校园综合招聘会，涵盖多个热门行业，欢迎毕业生提前准备简历。',
        type: '就业服务',
        image: getBase64FromImage('jobday.jpg')
      },
      { 
        tag: '通知', 
        title: '学生宿舍安全检查', 
        date: '2023-10-13',
        content: '本周三将开展校园安全大检查，重点检查宿舍违规电器、消防设施等，望配合。',
        type: '安全管理',
        image: getBase64FromImage('dorm.jpg')
      },
      { 
        tag: '公告', 
        title: '课程调整通知', 
        date: '2023-10-12',
        content: '因大型活动筹备，部分课程时间临时调整，具体见教务系统通知。',
        type: '教学服务',
        image: getBase64FromImage('class.jpg')
      }
    ]);
    // 话题图片转base64
    await HotTopic.insertMany([
      { 
        title: '校园运动场馆开放时间调整讨论', 
        count: 1258,
        content: '大家觉得运动场馆开放时间是否合理？晚上能否延长至22点？来聊聊你的想法！',
        tags: ['校园设施', '运动', '意见征集'],
        cover: getBase64FromImage('sports.jpg')
      },
      { 
        title: '期末考试时间安排讨论', 
        count: 986,
        content: '临近期末，有没有高效的复习计划？欢迎分享各科复习技巧和时间安排~',
        tags: ['学习', '期末', '经验交流'],
        cover: getBase64FromImage('exam.jpg')
      },
      { 
        title: '暑期社会实践分享会', 
        count: 753,
        content: '参加暑期实践的同学，来分享下你的收获和故事，给学弟学妹们点参考~',
        tags: ['实践', '暑期', '经验'],
        cover: getBase64FromImage('practice.jpg')
      }
    ]);
    await Activity.insertMany([
      { 
        title: '春季运动会', 
        description: '校级体育赛事，展现青春风采', 
        date: '2023-10-25',
        location: '学校体育场',
        cover: getBase64FromImage('sports.jpg')
      },
      { 
        title: '学术讲座周', 
        description: '多位教授带来前沿学术分享', 
        date: '2023-11-01',
        location: '学术报告厅',
        cover: getBase64FromImage('lecture.jpg')
      },
      { 
        title: '社团嘉年华', 
        description: '各大学生社团集中展示特色', 
        date: '2023-10-28',
        location: '体育馆广场',
        cover: getBase64FromImage('carnival.jpg')
      },
      { 
        title: '毕业生双选会', 
        description: '百家企业进校招聘应届生', 
        date: '2023-11-05',
        location: '就业中心',
        cover: getBase64FromImage('jobfair.jpg')
      },
      { title: '校园开放日', description: '邀请中学生体验大学生活', cover: '/downloads/class.jpg' },
      { title: '编程马拉松', description: '48小时极限开发挑战赛', cover: '/downloads/class.jpg' },
      { title: '文艺汇演', description: '各学院艺术团体联合演出', cover: '/downloads/class.jpg' },
      { title: '志愿者招募', description: '大型活动服务团队选拔', cover: '/downloads/class.jpg' },
      { title: '创新项目展', description: '学生科研成果集中展示', cover: '/downloads/class.jpg' },
      { title: '校友返校日', description: '毕业校友重返母校交流活动', cover: '/downloads/class.jpg' },
      { title: '实验室开放', description: '重点实验室参观体验活动', cover: '/downloads/class.jpg' },
      { title: '职业规划课', description: '知名企业HR现场指导', cover: '/downloads/class.jpg' },
      { title: '读书分享会', description: '师生共读经典著作交流', cover: '/downloads/class.jpg' },
      { title: '环保公益活动', description: '校园周边环境维护行动', cover: '/downloads/class.jpg' },
      { title: '国际交流周', description: '留学生文化交流系列活动', cover: '/downloads/class.jpg' }
    ]);
    await MarketItem.insertMany([
      { 
        title: '出九成新笔记本电脑',
        description: '配置i5处理器、8G内存、256G固态，使用两年，无维修记录，适合日常办公学习。', 
        price: 2800,
        category: '数码产品',
        contact: '微信：campus_flea01',
        cover: getBase64FromImage('market1.jpg')
      },
      { 
        title: '转让考研复习资料',
        description: '包含数学、英语、政治各科历年真题、笔记，2024考研适用，几乎全新。', 
        price: 80,
        category: '学习资料',
        contact: 'QQ：123456789',
        cover: getBase64FromImage('market2.jpg')
      },
      { 
        title: '全新运动耳机出售',
        description: '品牌降噪耳机，音质好，续航持久，原价499，现350出，支持验货。', 
        price: 350,
        category: '数码产品',
        contact: '电话：138xxxx1234',
        cover: getBase64FromImage('market1.jpg')
      },
      { 
        title: '考研资料打包出售',
        description: '数学一、英语一、408专业课资料，包含课本、习题集和模拟题。', 
        price: 150,
        category: '学习资料',
        contact: '微信：study_sell01',
        cover: getBase64FromImage('market2.jpg')
      },
      { description: '品牌背包特价处理', cover: '/downloads/market1.jpg' },
      { description: '英语四级真题资料', cover: '/downloads/market2.jpg' },
      { description: '数码相机低价出', cover: '/downloads/market1.jpg' },
      { description: '校园卡挂失转卖', cover: '/downloads/market2.jpg' },
      { description: '电子词典九成新', cover: '/downloads/market1.jpg' },
      { description: '四六级辅导书籍', cover: '/downloads/market2.jpg' },
      { description: '时尚手表求带走', cover: '/downloads/market1.jpg' },
      { description: '台灯文具套装组', cover: '/downloads/market2.jpg' },
      { description: '考研数学笔记', cover: '/downloads/market1.jpg' },
      { description: '运动鞋码42转让', cover: '/downloads/market2.jpg' },
      { description: '学生平板急售', cover: '/downloads/market1.jpg' }
    ]);
    console.log('首页模拟数据插入完成');
    process.exit();
  } catch (err) {
    console.error('❌ MongoDB 连接失败:', err.message);
    process.exit(1);
  }
}

seedHomeData();
